import requests
import json
import config.globalVariable as gv
import pandas as pd
from datetime import datetime

def getRiseFallCountData():
    '''
    获取涨跌数据
    :return: DataFrame
    '''
    uri = '/market_indicator/line?fields=rise_count,fall_count'
    return senGetRequest(uri)

def getYesterdayData():
    '''获取昨日涨停今日表现数据'''
    uri = '/market_indicator/line?fields=yesterday_limit_up_avg_pcp'
    return senGetRequest(uri)

def getUpDownData():
    '''涨跌对比'''
    uri = '/pool/detail?pool_name=limit_up'
    limit_up_count = senGetRequestFilterST(uri)
    uri = '/pool/detail?pool_name=limit_down'
    limit_down_count = senGetRequestFilterST(uri)
    result = {'limit_up_count': limit_up_count, 'limit_down_count': limit_down_count}
    return result

def getUpDataFrame():
    uri = '/pool/detail?pool_name=limit_up'
    dataAll = senGetRequestFilterSTList(uri)
    if dataAll is None:
        return
    dict = {0: '股票代码', 1: '股票名称', 2: '涨停板块', 3: '最新价', 4: '涨跌幅', 5: '封单比', 6: '换手率',
            7: '流通市值', 8: '首次封板', 9: '最后封板', 10: '开板', 11: '连板',12:'说明'}
    plate_data_all = pd.DataFrame()
    for item in dataAll:
        # 涨幅格式
        zf = str(round(item.get('change_percent') * 100, 2)) + '%'
        #封单比
        fdb = str(round(item.get('buy_lock_volume_ratio') * 100, 2)) + '%'
        #换手
        hsl = str(round(item.get('turnover_ratio') * 100, 2)) + '%'
        #市值
        ltsz = str(round(item.get('non_restricted_capital') / 100000000, 2)) + '亿'

        symbol = item.get('symbol')
        surge_reason = item.get('surge_reason')
        plate_name = ''
        plate_reasonAll = ''
        if surge_reason is not None:
            related_plates = surge_reason.get('related_plates')
            if related_plates is not None:
                for plate in related_plates:
                    plate_name +=plate.get('plate_name') + gv.JHFG
                plate_name = plate_name.rstrip(gv.JHFG)
                plate_reasonAll = ''
                for plate in related_plates:
                    plate_reason = plate.get('plate_reason')
                    if plate_reason is not None and len(plate_reason)>0:
                        plate_reasonAll += plate_reason + gv.FHFG

            plate_reasonAll += surge_reason.get('stock_reason') + gv.FHFG
            plate_reasonAll = plate_reasonAll.rstrip(gv.FHFG)
        first_limit_up = datetime.fromtimestamp(item.get('first_limit_up')).strftime('%H:%M:%S')
        last_limit_up = datetime.fromtimestamp(item.get('last_limit_up')).strftime('%H:%M:%S')
        break_limit_up_times = item.get('break_limit_up_times')
        limit_up_days = item.get('limit_up_days')
        item_data = [
            symbol[:symbol.find('.')],item.get('stock_chi_name'),plate_name,str(item.get('price')),
            zf,fdb,hsl,ltsz,
            first_limit_up,last_limit_up,str(break_limit_up_times) if break_limit_up_times!=0 else '-',
            str(limit_up_days) + '连板' if limit_up_days>1 else '首板',
            plate_reasonAll
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    return plate_data_all

def getUpDataFrame_char():
    uri = '/pool/detail?pool_name=limit_up'
    dataAll = senGetRequestFilterSTList(uri)
    if dataAll is None:
        return
    dict = {0: '股票代码', 1: '股票名称', 2: '涨停板块', 3: '最新价', 4: '涨跌幅', 5: '封单比', 6: '换手率',
            7: '流通市值', 8: '首次封板', 9: '最后封板', 10: '开板', 11: '连板',12:'说明'}
    plate_data_all = pd.DataFrame()
    result_time = None
    for item in dataAll:
        # 涨幅格式
        zf = str(round(item.get('change_percent') * 100, 2)) + '%'
        #封单比
        fdb = str(round(item.get('buy_lock_volume_ratio') * 100, 2)) + '%'
        #换手
        hsl = str(round(item.get('turnover_ratio') * 100, 2)) + '%'
        #市值
        ltsz = str(round(item.get('non_restricted_capital') / 100000000, 2)) + '亿'

        symbol = item.get('symbol')
        surge_reason = item.get('surge_reason')
        plate_name = ''
        plate_reasonAll = ''
        if surge_reason is not None:
            related_plates = surge_reason.get('related_plates')
            if related_plates is not None:
                for plate in related_plates:
                    plate_name +=plate.get('plate_name') + gv.JHFG
                plate_name = plate_name.rstrip(gv.JHFG)
                plate_reasonAll = ''
                for plate in related_plates:
                    plate_reason = plate.get('plate_reason')
                    if plate_reason is not None and len(plate_reason)>0:
                        plate_reasonAll += plate_reason + gv.FHFG

            plate_reasonAll += surge_reason.get('stock_reason') + gv.FHFG
            plate_reasonAll = plate_reasonAll.rstrip(gv.FHFG)
        first_limit_up = datetime.fromtimestamp(item.get('first_limit_up')).strftime('%H:%M:%S')
        last_limit_up = datetime.fromtimestamp(item.get('last_limit_up')).strftime('%H:%M:%S')
        #获取时间
        if result_time is None:
            result_time = datetime.fromtimestamp(item.get('last_limit_up')).strftime('%Y-%m-%d')
        break_limit_up_times = item.get('break_limit_up_times')
        limit_up_days = item.get('limit_up_days')
        item_data = [
            symbol[:symbol.find('.')],item.get('stock_chi_name'),plate_name,str(item.get('price')),
            zf,fdb,hsl,ltsz,
            first_limit_up,last_limit_up,str(break_limit_up_times) if break_limit_up_times!=0 else '-',
            limit_up_days,
            plate_reasonAll
        ]
        # 将数据转换成DataFrame类型
        data = pd.DataFrame(item_data).T
        data.rename(columns=dict, inplace=True)
        plate_data_all = plate_data_all._append(data, ignore_index=True)
    return plate_data_all,result_time
def getBrokenData():
    '''炸板'''
    uri = '/market_indicator/line?fields=limit_up_broken_count,limit_up_broken_ratio'
    result = senGetRequest(uri)
    uri = '/pool/detail?pool_name=limit_up_broken'
    limit_up_broken_count = senGetRequestFilterST(uri)
    result['limit_up_broken_count'] = limit_up_broken_count
    return result

def getTemperatureData():
    '''热度'''
    uri = '/market_indicator/line?fields=market_temperature'
    return senGetRequest(uri)

def getriseData(code):
    '''涨幅'''
    uri = '/real?fields=prod_name,px_change_rate&prod_code='+code
    return senGetRequest(uri)



def senGetRequest(uri):
    '''发送GEt请求'''
    if uri.find('real') !=-1:
        url = gv.xugubaoRealApiAddress + uri
    else:
        url = gv.xugubaoApiAddress + uri
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    code = data.get('code')
    if code != 20000:
        print(data.get('message'))
        return None
    dataList = data.get('data')
    if dataList is None or len(dataList) <= 0:
        return None
    if uri.find('real') != -1:
        result  = dataList.get('snapshot')
    else:
        result = dataList[-1]
    return result

def senGetRequestFilterSTList(uri):
    '''发送GEt请求'''
    url = gv.xugubaoApiAddress + uri
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    code = data.get('code')
    if code != 20000:
        print(data.get('message'))
        return None
    dataList = data.get('data')
    if dataList is None or len(dataList) <= 0:
        return None
    i = 0
    for index in range(len(dataList)):
        item = dataList[i]
        stock_type = item.get('stock_type')
        if stock_type is None or stock_type == 1 or stock_type == 5:
            del dataList[i]
            i -= 1
        i+=1
    return dataList

def senGetRequestFilterST(uri)->int:
    '''发送GEt请求'''
    url = gv.xugubaoApiAddress + uri
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200:
        return None
    # 解析JSON数据
    data = json.loads(response.text)
    code = data.get('code')
    if code != 20000:
        print(data.get('message'))
        return None
    dataList = data.get('data')
    if dataList is None or len(dataList) <= 0:
        return None
    num = 0
    for item in dataList:
        stock_type = item.get('stock_type')
        if stock_type is not None and stock_type != 1 and stock_type != 5:
            num+=1
    return num

if __name__ == '__main__':
    date = datetime.today().date()
    print(date)
    date_str = '2024-09-07'
    date_obj = datetime.strptime(date_str, '%Y-%m-%d').date()
    print(date_obj)